﻿using AutoMapper;
using MediatR;
using Process.API.Application.Command.Action.ProductionProcess;
using Process.Domain;
using Process.ErrorCode;
using Process.Infrastructure.Implement;

namespace Process.API.Application.Handler.Action.ProductionProcess
{
    public class UpdProductionProcessTableHandler : IRequestHandler<UpdProductionProcessTableCommand, APIResult<int>>
    {
        private readonly DatabaseContext db;

        public UpdProductionProcessTableHandler(DatabaseContext db)
        {
            this.db = db;
        }

        public async Task<APIResult<int>> Handle(UpdProductionProcessTableCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();

            if (request.ProductionOrdersId == 0 || request.ProcessNumber == 0)
            {
                result.Code = APIEnum.Fail;
                result.Message = "生产工单ID与工序步骤必须提供";
                result.Data = 0;
                return await Task.FromResult(result);
            }

            // 1) 逻辑删除：该工单在该工序步骤下的所有现有记录
            await db.SqlSugar
                .Updateable<ProductionProcessTable>()
                .SetColumns(x => new ProductionProcessTable { IsDel = true })
                .Where(x => x.ProductionOrdersId == request.ProductionOrdersId && x.ProcessNumber == request.ProcessNumber && x.IsDel == false)
                .ExecuteCommandAsync();

            // 2) 批量新增：为该步骤写入新的工序ID集合
            if (request.ProcessIds != null && request.ProcessIds.Count > 0)
            {
                var toInsert = request.ProcessIds.Distinct().Select(pid => new ProductionProcessTable
                {
                    ProductionOrdersId = request.ProductionOrdersId,
                    ProcessNumber = request.ProcessNumber,
                    ProcessId = pid,
                    IsDel = false
                }).ToList();

                var inserted = await db.SqlSugar.Insertable(toInsert).ExecuteCommandAsync();
                result.Data = inserted;
            }
            else
            {
                result.Data = 0;
            }

            result.Code = APIEnum.Ok;
            result.Message = "生产工单工序更新成功";
            return await Task.FromResult(result);
        }
    }
}
